//
//  SegmentView.swift
//  CustomSegmentView
//
//  Created by haisheng huang on 15/11/16.
//  Copyright © 2015年 haisheng huang. All rights reserved.
//

import UIKit

public enum SegmentStyle {
    case Default
    case TitleAndIcon  //还没有设计
}


@objc public protocol SegmentViewDelegate: NSObjectProtocol {
    
    @available(iOS 7.0, *)
    optional func segmentView(segmentView: SegmentView, didSelectedItemAtIndex index: Int)
    
    @available(iOS 7.0, *)
    optional func segmentView(segmentView: SegmentView, shouldSelectedItemAtIndex index: Int ) -> Bool
    
}

@objc public class SegmentView: UIView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    private var sIcons: NSArray?
    private var sTitles: NSArray?
    var sStyle: SegmentStyle? = SegmentStyle.Default {
        
        willSet(newValue) {
            
            if newValue == nil {
                return
            }
            
        }
        
        didSet {
            
        }
    }
    var delegate: SegmentViewDelegate?
    var indicatorLine: UIView?
    var normalColor: UIColor? = UIColor(white: 0.4, alpha: 1.0) {
        
        willSet(newValue) {
            
        }
        
        didSet {
            
        }
        
    }
    var highlightedColor: UIColor = UIColor(red: 0.0, green: 193.0/255.0, blue: 200.0/255.0, alpha: 1.0) {
    
        willSet(newValue) {
        
        }
        
        didSet {
        
            
        }
    }
    
    var currentHighlightedItem: UIView?
    var currentHighlightedTag: Int = 0
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        self.delegate = nil
    }
    
    public convenience init(frame: CGRect, titles: NSArray, icons: NSArray?, style: SegmentStyle?) {
        
        self.init(frame: frame)
        
        self.sTitles = titles
        self.sIcons = icons
        self.sStyle = style
        
        
        if (style == nil) || (style == SegmentStyle.Default) {
            self.loadDefaultSegmentView(frame, titles: titles)
        }
        
        self.addItemMidLine()
        
        self.addBottomLine()
        
        self.addIndicatorLineView(self.highlightedColor, frame: CGRectMake(0.0, self.frame.height - 2.5, self.frame.width / CGFloat((self.sTitles?.count)!), 2.5))
        
    }
    
    private func loadDefaultSegmentView(frame: CGRect, titles: NSArray) {
        
        let width: CGFloat = frame.size.width/CGFloat(titles.count)
        
        for i in 0...titles.count-1 {
            
            let button: UIButton = UIButton(type: UIButtonType.Custom)
            button.frame = CGRectMake(width*CGFloat(i), 0.0, width, frame.size.height)
            button.setTitle(titles[i] as? String, forState: UIControlState.Normal)
            button.tag = i
            button.addTarget(self, action: "itemButtonsAction:", forControlEvents: UIControlEvents.TouchUpInside)
            self.addSubview(button)
            
            //默认第一个被选中
            if i == 0 {
                button.setTitleColor(self.highlightedColor, forState: UIControlState.Normal)
                self.currentHighlightedTag = i
                self.currentHighlightedItem = button
            } else {
                button.setTitleColor(self.normalColor, forState: UIControlState.Normal)
            }
        }
        
    }
    
    //还没有设计
    private func loadTitleAndIconSegmentView() {
    
        
    }
    
    //一定要在load＊view的调用后调用
    private func addIndicatorLineView(color: UIColor, frame: CGRect) {
        
        let lineView: UIView = UIView(frame: frame)
        lineView.backgroundColor = color
        self.addSubview(lineView)
        self.indicatorLine = lineView

    }
    
    //indicatorView的变动
    func setIndicatorLineViewHighlightedAtIndex(index: Int) {
        
        let width: CGFloat = self.frame.size.width/CGFloat(self.sTitles!.count)
        var tempFrame: CGRect = (self.indicatorLine?.frame)!
        tempFrame.origin.x = width * CGFloat(index)
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.indicatorLine?.frame = tempFrame
            }) { (finish) -> Void in
                
        }
    }
    
    //item的handler
    func itemButtonsAction(sender: UIButton){
        
        print("button clicked")
        
        //重复选择判断
        guard self.currentHighlightedTag != sender.tag else {
            return
        }
        
        //delegate是否为空和是否实现该代理方法判断
        guard ((self.delegate?.segmentView?(self, didSelectedItemAtIndex: sender.tag)) != nil) else {
            return
        }
        
        print("button clicked delegate success!")
        
        //移动指示线
        self.setIndicatorLineViewHighlightedAtIndex(sender.tag)
        
        //重置就的高亮选项
        self.setItemNormalStatus(self.currentHighlightedItem!)
        
        //设置新的高亮项
        self.currentHighlightedItem = sender
        self.currentHighlightedTag = sender.tag
        self.setCurrentItemHighlightedStatus()
        
    }
    
    public func setNormalColor(color: UIColor, animated: Bool) {
        
        self.normalColor = color
        
        if animated == true {
            
        }
    }
    
    public func setHighlightedColor(color: UIColor, animated: Bool) {
        
        self.highlightedColor = color
        
        if animated == true {
        
        }
    }
    
    public func setSStyle(style: SegmentStyle, animated: Bool) {
    
        self.sStyle = style
        
        if animated == true {
            
        }
        
    }
    
    //添加底部灰线
    public func addBottomLine() {
        
        let lineView: UIView = UIView(frame: CGRectMake(0.0, self.frame.height - 0.5, self.frame.width, 0.5))
        lineView.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
        self.addSubview(lineView)
        
    }
    
    //添加item间的线
    public func addItemMidLine() {
        
        if self.sTitles != nil && self.sTitles?.count > 2 {
            let width: CGFloat = self.frame.width / CGFloat((self.sTitles?.count)!)
            for i in 1...self.sTitles!.count - 1 {
                
                let midLine: UIView = UIView(frame: CGRectMake(width * CGFloat(i), 0.5, 0.5, self.frame.height - 1.0))
                midLine.backgroundColor = UIColor(white: 0.85, alpha: 1.0)
                self.addSubview(midLine)
            }
        }
        
    }
    
    //设置当前高亮选项的状态
    func setCurrentItemHighlightedStatus() {
        
        (self.currentHighlightedItem as! UIButton).setTitleColor(self.highlightedColor, forState: UIControlState.Normal)
        self.setIndicatorLineViewHighlightedAtIndex(self.currentHighlightedTag)
    }
    
    //设置选项的正常状态 （以后可以拆解item）
    func setItemNormalStatus(itemView:UIView) {
    
        (itemView as! UIButton).setTitleColor(self.normalColor, forState: UIControlState.Normal)
        
    }
    
    //手动设置高亮选项
    func setHighlightedItemAtIndex(index: Int) {
        
        for view in self.subviews {
            
            guard (view is UIButton) else { return }
            
            if view.tag == index {
                self.currentHighlightedItem = view
                self.currentHighlightedTag = index
                self.setCurrentItemHighlightedStatus()
            } else {
                self.setItemNormalStatus(view)
            }
        }
    }
    
    
    
}
